angular.module("application.services")
.factory('lessonProcess', function($http, $q, BASE_URL, $location) {
	return {
		getData: function(lsId) {
			return $http.post(BASE_URL + 'index.php/application_api/lesson/getLessonContent/'+ lsId)
			.then(function(promise) {
				if(promise.data == 'null')
					$location.path('/error/' + lsId);
				
				data = promise.data;
				return {
					title: data.title,
					content: data.content,
					timeline: data.timeline,
					cat: data.cat,
					questions: data.questions
				}
			});
		},
		getCat: function(catId) {
			return $http.post(BASE_URL + 'application_api/category/getHeaderCat/' + catId)
			.then(function(prm) {
				return prm.data;
			})
		},
		timelineRender: function(tlData) {
			$('.timeline-view .content').html("");
			for(i in tlData) {
				p1 = $('.page-view .lessoncontent p[index="' + tlData[i] + '"').get(0);
				p2 = $(p1).clone();
				$('.timeline-view .content').append(p2);
			};

			if($(".timeline-view .content .multimedia").length) {
				$(".timeline-view .multimedia iframe").each(function() {
					id = $(this).attr('id');
					$(this).attr('id', 'timeline-'+id);
				})
			}
		},
		stopVideos: function() {
			ids = [];
			$('.multimedia iframe').each(function() {
				id = $(this).attr("id");
				ids.push(id);
			});
			angular.forEach(ids, function(id) {
				iframe = document.getElementById(id);
				iframe.src = iframe.src;
				iframe.contentWindow.postMessage('{"event":"command","func":"' +'stopVideo' + '","args":""}', '*'); 
			})	 
		},
		sliderList: function(listId) {
			
			var $frame = $(listId);
			var $wrap  = $frame.parent();

			// Call Sly on frame
			$frame.sly({
				horizontal: 1,
				itemNav: 'centered',
				smart: 1,
				activateOn: 'click',
				mouseDragging: 1,
				touchDragging: 1,
				releaseSwing: 1,
				startAt: 1,
				scrollBar: $wrap.find('.scrollbar'),
				scrollBy: 1,
				speed: 300,
				elasticBounds: 1,
				easing: 'easeOutExpo',
				dragHandle: 1,
				dynamicHandle: 1,
				clickBar: 1,

				// Buttons
				prev: $wrap.find('.prev'),
				next: $wrap.find('.next'),
				prevPage: $wrap.find('.prevPage'),
				nextPage: $wrap.find('.nextPage')
			});

			$(listId + ' li').mousedown(function(event) {
				event.preventDefault();
				// return false;
			});
		}
	};
});

//===========================================================================================
//===========================================================================================
//===========================================================================================
angular.module("application.services")
.factory('mapProcess', function($http, $q, BASE_URL) 
{
	var listMap = [];
	var timelineMap;
	var basicStyle = [{"featureType":"road","stylers":[{"visibility":"off"}]}];
	var myStyle = [{"featureType":"road","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels.text.fill","stylers":[{"weight":0.8},{"color":"#DAD5CC"}]},{"featureType":"administrative","elementType":"geometry","stylers":[{"visibility":"on"},{"weight":0.8},{"color":"#DAD5CC"}]},{"featureType":"administrative.country","elementType":"geometry.stroke","stylers":[{"weight":1.1},{"color":"#b16736"}]},{"featureType":"administrative","elementType":"labels","stylers":[{"visibility":"on"},{"weight":0.1},{"color":"#e1e1e1"}]},{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#f0ece6"}]},{"featureType":"poi","stylers":[{"visibility":"off"}]},{"featureType":"transit","stylers":[{"visibility":"off"}]}];

	mapConfig = [
		{center: {lat: 15.961329, lng: 106.259766}, zoom: 5},
		{center: {lat: 38.5997, lng: 51.5039 }, zoom: 2}
	]

	// Initialize Static Map
	var mapOptions = {
		mapTypeControlOptions: {
			mapTypeIds: ['mystyle', google.maps.MapTypeId.TERRAIN]
		},
		scrollwheel: false,
		mapTypeId: 'mystyle',
		disableDoubleClickZoom: false,
		mapTypeControl: false,
		zoomControl: true,
		streetViewControl: false,

		center: { lat: 15.961329, lng: 106.259766},
		zoom: 5
	};
			
	return {
		intialTimelineMap: function() 
		{
			// Edit map configuration in Data
			mapOptions.center = mapConfig[0].center;
			mapOptions.zoom = mapConfig[0].zoom;

			// Load Map in Timeline View =============================================================
			//========================================================================================
			timelineMap = new google.maps.Map(document.getElementById("timeline-map"),mapOptions);
			timelineMap.mapTypes.set('mystyle',new google.maps.StyledMapType(myStyle,{ name:'My Style'}));
		},
		initialMap: function(mapId) {
			// Get Maps data in API ===============================================================
			setMap(mapId, 0);
		},
		resizeMap: function() {
			for(m in listMap) {
				google.maps.event.trigger(listMap[m], "resize");
			}
			google.maps.event.trigger(timelineMap, "resize");
		},
		setTimelineMap: function(id) {
			setMap(id, 1);
		}
	}

	function setMap(mapId, type) {
		var map;
		var infoLast;
		$http.get(BASE_URL + 'index.php/application_api/lesson/getLessonMaps/' + mapId)
		.then(function(promise) {
			mapData = promise.data;

			// Edit map configuration in Data
			mapOptions.center = {
				lat: parseFloat(mapData.center[0]), 
				lng: parseFloat(mapData.center[1])
			};
			mapOptions.zoom = parseInt(mapData.zoom);
			console.log(mapData);
			console.log(mapOptions);

			//Create and Render Map
			if(type == 0)
				map = new google.maps.Map(document.getElementById(mapId), mapOptions);
			else if(type == 1)
				map = new google.maps.Map(document.getElementById('timeline-map'), mapOptions);
			else return false;

			map.mapTypes.set('mystyle',new google.maps.StyledMapType(myStyle,{ name:'My Style'}));
			google.maps.event.addListener(map, 'click', function() {
				if(infoLast) {
					infoLast.close();
				}
			})

			//Get Polygon Elements ===========================================================================
			//================================================================================================
			polygonJSON = mapData.polygons;
			if(polygonJSON && polygonJSON.length > 0) {
				for(poly in polygonJSON) 
				{
					coord = [];
					// Convert String to Array
					coor = polygonJSON[poly].coordinate;
					coor = coor.split(' ');
					for(j in coor) {
						coor[j] = coor[j].split(',');
					}

					//Add data to $coord
					for(j in coor) {
						point = new google.maps.LatLng(coor[j][1], coor[j][0]);
						coord.push(new google.maps.LatLng(coor[j][1], coor[j][0]));
					}
					polygon = new google.maps.Polygon({
						paths: coord,
						strokeColor: polygonJSON[poly].color,
						strokeOpacity: 0.8,
						strokeWeight: 1,
						fillColor: polygonJSON[poly].color,
						fillOpacity: 0.35
					});

					//Get Center of Polygon
					var bounds = new google.maps.LatLngBounds();
					for(i = 0; i < coord.length; i++) {
						bounds.extend(coord[i]);
					}
					polyCenter = bounds.getCenter();

					// Info Description window on click
					info = new google.maps.InfoWindow();
					content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  polygonJSON[poly].description +"</div>";
					
					polygon.setMap(map);

					// Using CLOSURE Code Style
					google.maps.event.addListener(polygon, 'click', (function(polygon, content, info, polyCenter) {
						return function() {
							if(infoLast) {
								infoLast.close();
							}
							info.setContent(content);
							info.setPosition(polyCenter); 
							info.open(map);
							infoLast = info;
						}
					})(polygon, content, info, polyCenter));
				}									
			} // End Polygons Process

			// Get Polyline Elements ===========================================================================
			// ================================================================================================
			polylineJSON = mapData.polylines;
			if(polylineJSON && polylineJSON.length > 0) {
				for(line in polylineJSON) 
				{
					coord = [];
					// Convert String to Array
					coor = polylineJSON[line].coordinate;
					coor = coor.split(' ');
					for(j in coor) {
						coor[j] = coor[j].split(',');
					}

					//Add data to $coord
					for(j in coor) {
						point = new google.maps.LatLng(coor[j][1], coor[j][0]);
						coord.push(new google.maps.LatLng(coor[j][1], coor[j][0]));
					}
					polylineConfig = {
						path: coord,
						strokeColor: polylineJSON[line].color,
						strokeOpacity: 0.8,
						strokeWeight: 3
					}
					icons = [];
					if(polylineJSON[line].arrow == true) {
						var arrowSymbol = {
							path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
							strokeOpacity: 1,
						};
						iconArrow = {
							icon: arrowSymbol,
							offset: "100%"
						};
						icons.push(iconArrow);
					}
					if(polylineJSON[line].style == "dashed") {
						var lineSymbol = {
							path: 'M 0,-1 0,1',
							strokeOpacity: 1,
							scale: 4
						};
						dashLine = {
							icon: lineSymbol,
							offset: "0",
							repeat: '20px'
						};
						icons.push(dashLine);
						polylineConfig.strokeOpacity = 0.1;
					}
					polylineConfig.icons = icons;

					polyline = new google.maps.Polyline(polylineConfig);
					//Get Center of polyline
					var bounds = new google.maps.LatLngBounds();
					for(i = 0; i < coord.length; i++) {
						bounds.extend(coord[i]);
					}
					polyCenter = bounds.getCenter();

					// Info Description window on click
					info = new google.maps.InfoWindow();
					content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  polylineJSON[line].description +"</div>";
					
					polyline.setMap(map);

					// Using CLOSURE Code Style
					google.maps.event.addListener(polyline, 'click', (function(polyline, content, info, polyCenter) {
						return function() {
							if(infoLast) {
								infoLast.close();
							}
							info.setContent(content);
							info.setPosition(polyCenter); 
							info.open(map);
							infoLast = info;
						}
					})(polyline, content, info, polyCenter));
				}									
			} // End polylines Process

			// Get Marker Elements ===========================================================================
			// ================================================================================================
			markerJSON = mapData.markers;
			if(markerJSON && markerJSON.length > 0) {
				for(p in markerJSON) 
				{
					coord = markerJSON[p].coordinate.split(",");
					point = new google.maps.LatLng(coord[1], coord[0]);

					marker = new google.maps.Marker({
						position: point,
						title: "Vị trí"
					});

					// Info Description window on click
					info = new google.maps.InfoWindow();
					content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  markerJSON[p].description +"</div>";
					
					marker.setMap(map);

					// Using CLOSURE Code Style
					google.maps.event.addListener(marker, 'click', (function(marker, content, info) {
						return function() {
							if(infoLast) {
								infoLast.close();
							}
							info.setContent(content);
							info.open(map, marker);
							infoLast = info;
						}
					})(marker, content, info));
				}									
			}; // End polylines Process	

			// Get Ground Elements ===========================================================================
			// ================================================================================================
			groundJSON = mapData.grounds;
			if(groundJSON && groundJSON.length > 0) {
				for(p in groundJSON) 
				{
					sw = groundJSON[p].sw.split(',');
					ne = groundJSON[p].ne.split(',');
					var imageBounds = new google.maps.LatLngBounds(
						new google.maps.LatLng(sw[0], sw[1]),
						new google.maps.LatLng(ne[0], ne[1])
					)
					boundCenter = imageBounds.getCenter();

					ground = new google.maps.GroundOverlay(groundJSON[p].url, imageBounds);
					ground.setMap(map);

					// Info Description window on click
					info = new google.maps.InfoWindow();
					content = "<div class='infowindow-content' style='min-width: 200px; min-height: 100px'>"+  groundJSON[p].description +"</div>";

					// Using CLOSURE Code Style
					google.maps.event.addListener(ground, 'click', (function(ground, content, info, boundCenter) {
						return function() {
							if(infoLast) {
								infoLast.close();
							}
							info.setContent(content);
							info.setPosition(boundCenter);
							info.open(map);
							infoLast = info;
							console.log(boundCenter);
						}
					})(ground, content, info, boundCenter));
				}									
			}; // End Grounds Process				

			if(type == 0) listMap.push(map);
		});
	}
});

//===========================================================================================
//===========================================================================================
//===========================================================================================
angular.module("application.services")
.factory('commentProcess', function($http, BASE_URL) {
	return {
		loadCommentData: function(lessonId) {
			parentCmtArr = [];
			childCmtArr = [];
			return $http.post(BASE_URL + '/index.php/application_api/comment/getcmtdata/' + lessonId)
			.then(function(promise) {
				angular.forEach(promise.data, function(cmt) {
					if(!cmt.parent) {
						cmt.childs = [];
						parentCmtArr.push(cmt);
					}
					else childCmtArr.push(cmt);
				});
				angular.forEach(parentCmtArr, function(cmt) {
					angular.forEach(childCmtArr, function(child) {
						if(child.parent == cmt._id.$id) {
							cmt.childs.push(child);
						}
					})
				});
				console.log(parentCmtArr);
				return parentCmtArr;
			});
		},
		addTopic: function(str, lsId, parent) {
			console.log(parent);
			return $http({
				url: BASE_URL + 'index.php/application_api/comment/addComment',
				method: "POST",
				data: $.param({cmt: str, lsid: lsId, par: parent}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(promise) {
				return promise.data;
			})
		}
	}
})
.factory('questionProcess', function($http, BASE_URL) {
	return {
		loadQuestions: function(questions) {
			return $http({
				url: BASE_URL + 'index.php/application_api/question/getQuestions',
				method: "POST",
				data: $.param({ids: questions}),
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).then(function(promise) {
				return promise.data;
			})
		}
	}
})

